package com.wandong.cinema.service.impl;

import com.wandong.cinema.entity.Admin;
import com.wandong.cinema.entity.Manager;
import com.wandong.cinema.entity.Receptionist;
import com.wandong.cinema.entity.User;
import com.wandong.cinema.service.UserService;
import com.wandong.cinema.util.IdGenerator;
import com.wandong.cinema.util.InputUtil;
import com.wandong.cinema.util.LogUtil;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

public class UserServiceImpl implements UserService {
    // 存储所有用户，用户名作为键（唯一）
    private static final Map<String, User> USER_MAP = new ConcurrentHashMap<>();
    
    // 初始化默认管理员
    static {
        try {
            User admin = new Admin(
                IdGenerator.generateUserId("ADMIN"),
                "admin",
                "ynuinfo#777",
                new Date(),
                "ADMIN",
                "13800138000"
            );
            USER_MAP.put("admin", admin);
            LogUtil.log("系统初始化：添加默认管理员 admin");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public User login(String username, String password) throws Exception {
        if (!USER_MAP.containsKey(username)) {
            throw new Exception("用户名不存在");
        }
        
        User user = USER_MAP.get(username);
        if (!user.getPassword().equals(password)) {
            throw new Exception("密码错误");
        }
        
        LogUtil.log("用户登录：" + username + "(" + user.getUserType() + ")");
        return user;
    }

    @Override
    public void addUser() {
        try {
            System.out.println("\n=== 添加用户 ===");
            System.out.print("请输入用户名: ");
            String username = InputUtil.inputString();
            
            if (USER_MAP.containsKey(username)) {
                System.out.println("用户名已存在");
                return;
            }
            
            System.out.print("请输入密码: ");
            String password = InputUtil.inputString();
            System.out.print("请输入手机号: ");
            String phone = InputUtil.inputString();
            System.out.println("请选择用户类型: 1-管理员, 2-经理, 3-前台");
            int typeChoice = InputUtil.inputInteger();
            
            String userType;
            User user;
            String userId = "";
            
            switch (typeChoice) {
                case 1:
                    userType = "ADMIN";
                    userId = IdGenerator.generateUserId("ADMIN");
                    user = new Admin(userId, username, password, new Date(), userType, phone);
                    break;
                case 2:
                    userType = "MANAGER";
                    userId = IdGenerator.generateUserId("MANAGER");
                    user = new Manager(userId, username, password, new Date(), userType, phone);
                    break;
                case 3:
                    userType = "RECEPTIONIST";
                    userId = IdGenerator.generateUserId("RECEPTIONIST");
                    user = new Receptionist(userId, username, password, new Date(), userType, phone);
                    break;
                default:
                    System.out.println("无效的用户类型");
                    return;
            }
            
            USER_MAP.put(username, user);
            LogUtil.log("添加用户：" + username + "(" + userType + "), ID: " + userId);
            System.out.println("用户添加成功");
        } catch (Exception e) {
            System.out.println("添加用户失败: " + e.getMessage());
        }
    }

    @Override
    public void deleteUser() {
        System.out.println("\n=== 删除用户 ===");
        System.out.print("请输入要删除的用户名: ");
        String username = InputUtil.inputString();
        
        if (!USER_MAP.containsKey(username)) {
            System.out.println("用户名不存在");
            return;
        }
        
        // 不能删除默认管理员
        if ("admin".equals(username)) {
            System.out.println("不能删除默认管理员");
            return;
        }
        
        User user = USER_MAP.remove(username);
        LogUtil.log("删除用户：" + username + "(" + user.getUserType() + ")");
        System.out.println("用户删除成功");
    }

    @Override
    public void updateUser() {
        System.out.println("\n=== 修改用户 ===");
        System.out.print("请输入要修改的用户名: ");
        String username = InputUtil.inputString();
        
        if (!USER_MAP.containsKey(username)) {
            System.out.println("用户名不存在");
            return;
        }
        
        User user = USER_MAP.get(username);
        System.out.print("请输入新手机号(回车不修改): ");
        String newPhone = InputUtil.inputString();
        if (!newPhone.isEmpty()) {
            user.setPhone(newPhone);
        }
        
        System.out.println("请选择新用户类型(1-管理员, 2-经理, 3-前台, 0-不修改): ");
        int typeChoice = InputUtil.inputInteger();
        if (typeChoice >= 1 && typeChoice <= 3) {
            String newType = typeChoice == 1 ? "ADMIN" : (typeChoice == 2 ? "MANAGER" : "RECEPTIONIST");
            // 不能修改默认管理员的类型
            if (!"admin".equals(username)) {
                user.setUserType(newType);
                LogUtil.log("修改用户类型：" + username + " 从 " + user.getUserType() + " 改为 " + newType);
            } else {
                System.out.println("不能修改默认管理员的类型");
            }
        }
        
        USER_MAP.put(username, user);
        System.out.println("用户修改成功");
    }

    @Override
    public void queryUsers() {
        System.out.println("\n=== 用户查询 ===");
        System.out.println("1-查询所有用户 2-按类型查询");
        int choice = InputUtil.inputInteger();
        
        List<User> result = new ArrayList<>();
        
        if (choice == 1) {
            result.addAll(USER_MAP.values());
        } else if (choice == 2) {
            System.out.println("请选择用户类型: 1-管理员, 2-经理, 3-前台");
            int typeChoice = InputUtil.inputInteger();
            String targetType = typeChoice == 1 ? "ADMIN" : (typeChoice == 2 ? "MANAGER" : "RECEPTIONIST");
            
            for (User user : USER_MAP.values()) {
                if (user.getUserType().equals(targetType)) {
                    result.add(user);
                }
            }
        } else {
            System.out.println("无效选择");
            return;
        }
        
        if (result.isEmpty()) {
            System.out.println("没有找到符合条件的用户");
            return;
        }
        
        System.out.println("\n查询结果:");
        System.out.println("ID\t用户名\t类型\t手机号\t注册时间");
        for (User user : result) {
            System.out.printf("%s\t%s\t%s\t%s\t%s%n",
                    user.getUserId(),
                    user.getUsername(),
                    user.getUserType(),
                    user.getPhone(),
                    user.getRegisterTime());
        }
    }

    @Override
    public void resetPassword(String userId) {
        for (User user : USER_MAP.values()) {
            if (user.getUserId().equals(userId)) {
                user.setPassword("123456"); // 重置为默认密码
                LogUtil.log("重置密码：" + user.getUsername());
                System.out.println("密码重置成功，新密码为123456");
                return;
            }
        }
        System.out.println("用户不存在");
    }
}
